package com.rivues.task.resource;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.bean.TaskInfo;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.report.web.model.EventTask;
import com.rivues.module.report.web.model.RouteTask;
import com.rivues.module.report.web.model.TaskNode;
import com.rivues.module.report.web.model.TaskReport;
import com.rivues.module.report.web.model.TaskReportInfo;
import com.rivues.util.RivuTools;
import com.rivues.util.iface.report.R3Request;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.serialize.JSON;

public class EventTaskResource extends Resource {
	private final Logger log = LoggerFactory.getLogger(EventTaskResource.class); 
	private JobDetail job ;
	private User user; 
	private TaskReportInfo taskReportInfo ;
	
	/**
	 * 构造器
	 * @param job
	 */
	@SuppressWarnings("unchecked")
	public EventTaskResource(JobDetail job){
		this.job = job ;
		List<User> userList = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi", job.getOrgi())).add(Restrictions.eq("id" ,this.job.getUserid()))) ;
		if(userList.size()>0){
			user = userList.get(0) ;
		}
		if(this.job.getTaskinfo()!=null && this.job.getTaskinfo().length()>0){
			TaskInfo taskinfo = JSON.parseObject(job.getTaskinfo(), TaskInfo.class) ;
			this.taskReportInfo = (TaskReportInfo)taskinfo.getTargetObject() ;
			R3Request request = new R3Request();
			request.getSession().setAttribute(RivuDataContext.USER_SESSION_NAME, user) ;
			request.setParameters("ps", "200") ;
			/**
			 * 获取Report信息，然后开始对Report进行渲染，之后记录所有数据
			 */
			for(TaskReport taskReport : taskReportInfo.getReportList()){
				if(taskReport.getReportid()!=null){
					/**
					 * 第一步，获取PublishedReport
					 */
					/**
					 * 第二步，获取报表数据
					 */
					if(taskReport.getPublishedReport()!=null && taskReport.getPublishedReport().getReport()!=null)
					for(AnalyzerReportModel model : taskReport.getPublishedReport().getReport().getModel()){
						if(model.getPublishedcubeid()!=null){
							try {
								model.setReportData(RivuTools.getReportData(taskReport.getPublishedReport().getReport() , request , model , 1, 200)) ;
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
	
	@Override
	public void begin() throws Exception {
		
	}

	@Override
	public void end(boolean clear) throws Exception {
		this.job.getReport().setPages(0) ;
	}

	@Override
	public JobDetail getJob() {
		return job;
	}

	@Override
	public void process(OutputTextFormat meta, JobDetail job) {
		/**
		 * 根据 TaskNode的节点类型，渲染数据内容，然后调用外部接口（邮件、短信、导出等）
		 */
		TaskNode taskNode = (TaskNode) meta.getData().get("taskNode");
		if(taskNode.getTaskConfig()!=null){
			EventTask taskConfig = (EventTask) taskNode.getTaskConfig();
			try{
				taskConfig.process(taskReportInfo,job) ;
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
//		RivuTools.sendMail(email , publishedReport, report , values , this.taskInfo) ;
		/**
		 * 报表运算完成后发送邮件
		 */
	}

	@Override
	public OutputTextFormat next() throws Exception {
		OutputTextFormat outTextFormat = null ;
		if(this.taskReportInfo!=null && this.taskReportInfo.getTaskNodeList().size()>0){
			TaskNode taskNode = this.taskReportInfo.getTaskNodeList().remove(0) ;
			if(taskNode.getTaskConfig()!=null && taskNode.getTaskConfig() instanceof RouteTask){
				RouteTask route = (RouteTask) taskNode.getTaskConfig() ;
				/**
				 * 判断RouteTask的结果是否为True，如果为True则继续执行下一个节点，如果为False，则跳到下一个RouteTask节点上。
				 */
				boolean res = route.process(taskReportInfo, job) ;
				if(res){
					return next();
				}else{
					for(int i=0 ; i< this.taskReportInfo.getTaskNodeList().size() ; ){
						taskNode = this.taskReportInfo.getTaskNodeList().get(0) ;
						if(taskNode.getTaskConfig() instanceof RouteTask){
							/**
							 * 找到下一个 RouteTask节点，退出循环，执行下一次
							 */
							return next() ;
						}else{
							this.taskReportInfo.getTaskNodeList().remove(0);
						}
					}
				}
			}else{
				outTextFormat = new OutputTextFormat(job) ;
				outTextFormat.getData().put("taskNode", taskNode) ;
			}
		}
		return outTextFormat;
	}

	@Override
	public boolean isAvailable() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public OutputTextFormat getText(OutputTextFormat object) throws Exception {
		return object;
	}

	@Override
	public void rmResource() {
		
	}

	@Override
	public void updateTask() {
		
	}

	public TaskReportInfo getTaskReportInfo() {
		return taskReportInfo;
	}

	public void setTaskReportInfo(TaskReportInfo taskReportInfo) {
		this.taskReportInfo = taskReportInfo;
	}

}
